from contextlib import asynccontextmanager
import fastapi
from app.core.config.__logging__ import get_logger
from app.services.robot import FlexHandler
from dataclasses import dataclass, field
from app.core.exceptions import ErrorCode, ServerException
from fastapi import Request
from app.core.exceptions import RobotException

logger = get_logger("app.lifespan")

@dataclass
class AppInstance:
    flex_handler: FlexHandler

    def close(self):
        try:
            self.flex_handler.close()
        except RobotException as e:
            logger.info(f"Close robot fail, {e}")

async def set_instance() -> AppInstance:
    instance = AppInstance(
        flex_handler=FlexHandler()
    )
    return instance


@asynccontextmanager
async def lifespan(app: fastapi.FastAPI):
    try:
        logger.info("starting to init lifespan")
        instance = await set_instance()
        app.state.instance = instance
        logger.info("initial instance successful")
        yield
        logger.info("shut down server")
        if hasattr(app.state, "instance"):
            app.state.instance.close()
    except Exception as e:
        raise ServerException(error_code=ErrorCode.LIFE_SPAN_ERROR, detail=f"Initial instance failed, {e}")


async def get_instance(request: Request):
    return request.app.state.instance













